<template>
	<!-- 注：这个页面是一个公共弹窗，具体的页面数据在static中，我这边只能改了下弹窗设计稿中能看到的弹窗样式，看不到的没改 -->
  <modal :visible="visible" position="center">
    <view class="message-modal">
      <image v-if="template.haveCloseIcon" @click.stop="onClose" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/member_close.png" class="close"></image>
      <view v-if="template.title" class="title">{{ template.title }}</view>
      <image v-if="template.haveMemberIcon" :style="{paddingTop: template.title ? '20rpx' : '128rpx' }" class="img-icon"
        src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/member_icon.png" alt="">
      <view class="content">
        <view v-if="template.message" class="message" :class="{ 'align-center': template.alignCenter }">
          {{ template.message }}
        </view>
        <view class="btn-wrap" v-if="template.cancelText || template.confirmText" :class="{ 'single-btn': !template.cancelText }">
          <button v-if="template.cancelText" class="common-btn solid btn" @click.stop="onCancel">
            {{ template.cancelText }}
          </button>
          <block v-if="template.confirmText">
            <button v-if="template.getPhoneNumber" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
              class="common-btn btn">
              {{ template.confirmText }}
            </button>
            <button v-else-if="template.contactService" open-type="contact" show-message-card="true"
              class="common-btn btn">
              {{ template.confirmText }}
            </button>
            <button v-else class="common-btn btn" @click.stop="onConfirm" :class="template.isShowBigBtn ?'big_btn':''">
              {{ template.confirmText }}
            </button>
          </block>
        </view>
      </view>
      <view v-if="template.closeIcon" @click.stop="onClose" class="close macallan-icon mcl-close"></view>
			<image v-if="template.img" :src="template.img" class="top-img" mode="aspectFill" />
    </view>
  </modal>
</template>

<script>
  import modal from "../modal/modal.vue";
  import {
    HANDLE_TYPE,
    getMessageModalTemplate
  } from "./static";
  import {
    getTsProcessStatus,
    getTsCommonStatus
  } from "./utils";
  import registerController from "./RegisterController";
  import RegisterTracker from "./RegisterTracker";

  export default {
    name: "message-modal",
    components: {
      modal
    },
    props: {
      // 使用页面
      location: {
        type: String,
        default: "home",
      },
      tsActId: {
        type: String,
        default: "",
      },
    },
    data() {
      return {
        visible: false,
        template: {},
      };
    },
    methods: {
      open(template) {
        if (!template) {
          return;
        }
        if (template.key) {
          this.trackingByTemplate({
            ...template
          });
        }
        this.template = template;
        this.visible = true;
      },
      close() {
        this.visible = false;
      },
      async getHandle(handleType) {
        switch (handleType) {
          case HANDLE_TYPE.COMPLETE_INFO:
            this.completeInfo();
            return;
          case HANDLE_TYPE.JOIN_TS_ACTIVE:
            await this.joinTsActive();
            return;
          case HANDLE_TYPE.BIND:
            await this.bind();
            return;
          default:
            await this.close();
        }
      },
      // 完善信息
      completeInfo() {
        this.close();
        uni.navigateTo({
          // url: "/pages/customer/registerSetting",
          url: "/pages/customer/exclusiveRegister",
        });
      },
      // 业务结束
      finish(template) {
        this.$emit("finish", template || this.template);
      },
      // 参加TS活动
      async joinTsActive() {
        const res = await getTsProcessStatus(this.tsActId);
        RegisterTracker.targetSalesParticipateNow(
          this.template.key === "SUCCESS_JOIN_NEXT" ? "成功入会" : "成功绑定"
        );
        this.close();

        const {
          messageModalCode,
          path
        } = res;
        if (path) {
          uni.navigateTo({
            url: path
          });
          this.finish();
        } else {
          this.changeTemplate(messageModalCode);
        }
      },
      // 绑定手机号
      async bind() {
        let registerSuccess = false;
        const phoneNumber = registerController.phoneNumber;
        if (registerController.canRegister) {
          const result = await registerController.register();
          registerSuccess = result.joinMemberSuccess;
        }
        this.close();
        const res = await getTsCommonStatus(phoneNumber);
        // 这里强制变更模板(接口只能查出绑定成功, 期望是入会成功)
        let successType = "成功绑定";
        if (
          this.template.key === "AUTH_NOT_INVITED_NEW_MEMBER" &&
          res.messageModalCode === "SUCCESS_BIND_MESSAGE"
        ) {
          successType = "成功入会";
          res.messageModalCode = "SUCCESS_JOIN_MESSAGE";
        }
        if (registerSuccess) {
          RegisterTracker.targetSalesContinueToJoinVip({
            success: true,
            successType: successType,
          });
        } else {
          const nextTemplate = getMessageModalTemplate(
            "TARGET_SALES",
            res.messageModalCode
          );
          RegisterTracker.targetSalesContinueToJoinVip({
            success: false,
            failReason: nextTemplate?.message || "继续加入失败",
          });
        }
        this.changeTemplate(res.messageModalCode);
      },
      changeTemplate(messageModalCode, tsNotInvited) {
        const template = getMessageModalTemplate(
          this.tsActId ? "TARGET_SALES" : "NORMAL",
          messageModalCode,
          tsNotInvited
        );
        if (template) {
          this.open(template);
          getApp().commonssPopupTrack('PopupExposure', {}, this.tsActId ? "TARGET_SALES" : "NORMAL",
            messageModalCode, {})
        } else {
          this.close();
        }
      },
      async onGetPhoneNumber(ev) {
        uni.showLoading({
          title: "正在加载",
        });
        // 重新授权手机号
        const res = await registerController.getPhoneNumberData(ev, {
          location: this.location,
          tsActId: this.tsActId,
        });
        if (res.success) {
          uni.hideLoading();
          const {
            phoneNumber
          } = res.data;
          const phoneNumberReg = /^1\d{10}$/;
          this.close();
          const {
            key
          } = this.template;

          getApp().commonssPopupTrack('PopupClick', {}, this.template.type, this.template.key, {
            'button_name': this.template.confirmText
          })
          if (this.tsActId) {
            // 部分模板需要基于新的手机号, 重新判断TS活动状态
            const CHANGE_TEMPLATE_CODE = [
              "AUTH_CANCEL",
              "AUTH_NOT_INVITED_OLD_MEMBER",
              "AUTH_NOT_INVITED_NEW_MEMBER",
              "BIND_MEMBER_NO_ID",
              "BIND_NOT_MEMBER_NO_ID",
              "OVERSEAS_MEMBER"
            ];
            if (CHANGE_TEMPLATE_CODE.includes(key)) {
              await this.tsActiveRegister(phoneNumber);
              return;
            }
          } else {
            if (!phoneNumberReg.test(phoneNumber)) {
              uni.hideLoading();
              this.$emit('recheckUser', {
                messageModalCode: 'OVERSEAS_MEMBER',
              });
              return;
            }
            await this.recheckUser(phoneNumber);
            uni.hideLoading();
          }
        }
      },
      // 确认是否能加入TS
      async tsActiveRegister(_phoneNumber) {
        const phoneNumberReg = /^1\d{10}$/;
        const phoneNumber = _phoneNumber || registerController.phoneNumber;
        if (!phoneNumberReg.test(phoneNumber)) {
          uni.hideLoading();
          this.changeTemplate('OVERSEAS_MEMBER')
          return;
        }
        const result = await registerController.getTargetSaleStatus(
          phoneNumber,
          this.tsActId
        );
        const template = getMessageModalTemplate(
          "TARGET_SALES",
          result.messageModalCode
        );
        if (template?.doRegister) {
          const registerData = await registerController.register(phoneNumber);
          Object.assign(result, registerData);
        }
        if (result.joinMemberSuccess) {
          this.$emit("registerSuccess", result);
        }
        this.changeTemplate(result.messageModalCode);
      },
      // 重新确认手机号
      async recheckUser(phoneNumber) {
        const userCheckResult = await registerController.repeatUserCheck(
          phoneNumber
        );
        this.$emit("recheckUser", {
          messageModalCode: userCheckResult.messageModalCode,
        });
        if (userCheckResult.joinMemberSuccess) {
          this.$emit("registerSuccess", userCheckResult);
        }
      },
      async onConfirm() {
        const copy = {
          ...this.template
        };
        if (['去完善', '立即完善'].includes(copy.confirmText)) {
          this.trackingAuthPiigate(copy.confirmText);
        } else {
          getApp().commonssPopupTrack('PopupClick', {}, copy.type, copy.key, {
            'button_name': copy.confirmText
          })
        }
        await this.getHandle(this.template.confirmHandle);
        this.$emit("confirm", copy);
        if (copy.confirmFinish) {
          this.finish(copy);
        }
      },
      async onCancel() {
        const copy = {
          ...this.template
        };
        if (['稍后再看', '稍后完善'].includes(copy.cancelText)) {
          this.trackingAuthPiigate(copy.cancelText);
        } else {
          getApp().commonssPopupTrack('PopupClick', {}, copy.type, copy.key, {
            'button_name': copy.cancelText
          })
        }
        await this.getHandle(this.template.cancelHandle);
        this.$emit("cancel", copy);
        if (copy.cancelFinish) {
          this.finish(copy);
        }
      },
      onClose() {
        this.close();
        this.$emit("close", this.template);
        this.finish();
      },
      // 埋码
      trackingAuthPiigate(btnName) {
        this.$commonSensors.commonPopupClick('MemberInfoCompetePopupClick', '会员信息完善弹窗点击', btnName)
        RegisterTracker.authPiigate({
          btnName,
          registerType: this.tsActId ? "TARGET_SALES" : "NORMAL",
          popupName: this.template.key == "SUCCESS_BIND_HAS_MEMBER" ? "EB绑定成功弹窗" : "EB注册成功弹窗"
        });
      },
      // 埋码
      trackingByTemplate(t) {
        const {
          key,
          message
        } = t;
        if (this.tsActId) {
          /** 首页-特邀会场-进入会场失败 */
          const TS_EVENT_FAIL_REASON_MAPPING = {
            EVENT_NOT_INVITED_MEMBER: "非受邀人群",
            EVENT_NOT_STARTED: "活动未开始",
            EVENT_HAS_ENDED: "活动已结束",
          };
          const failReason = TS_EVENT_FAIL_REASON_MAPPING[key];
          if (failReason) {
            RegisterTracker.targetSalesFailToParticipate(
              failReason,
              this.location
            );
          }
          /** 首页-特邀会场-授权手机号入会/绑定结果 */
          const TS_JOIN_VIP_RESULT_MAPPING = {
            BIND_MEMBER_NO_ID: {
              success: false
            },
            BIND_NOT_MEMBER_NO_ID: {
              success: false
            },
            // AUTH_NOT_INVITED_OLD_MEMBER: { success: false },
            // AUTH_NOT_INVITED_NEW_MEMBER: { success: false },
            SUCCESS_JOIN_NEXT: {
              success: true,
              successType: "成功入会"
            },
            SUCCESS_BIND_NEXT: {
              success: true,
              successType: "成功绑定"
            },
            SUCCESS_JOIN_MESSAGE: {
              success: true,
              successType: "成功入会"
            },
            SUCCESS_BIND_MESSAGE: {
              success: true,
              successType: "成功绑定"
            },
            FAIL_NO_ID: {
              success: false
            },
            FAIL_HAS_ID: {
              success: false
            },
            FAIL_NOT_MEMBER: {
              success: false
            },
          };
          const TS_JOIN_VIP_RESULT_MAPPING_TMP = TS_JOIN_VIP_RESULT_MAPPING[key];
          if (TS_JOIN_VIP_RESULT_MAPPING_TMP) {
            const TS_JOIN_VIP_RESULT_MAPPING_FAIL_REASON =
              TS_JOIN_VIP_RESULT_MAPPING_TMP.success ? "" : message;
            RegisterTracker.targetSalesJoinVipResult({
              ...TS_JOIN_VIP_RESULT_MAPPING_TMP,
              failReason: TS_JOIN_VIP_RESULT_MAPPING_FAIL_REASON,
            });
          }
        } else {
          /** 小程序-授权手机号入会/绑定结果 */
          const JOIN_VIP_RESULT_MAPPING = {
            SUCCESS_BIND_HAS_MEMBER: {
              success: true,
              successType: "成功绑定"
            },
            SUCCESS_BIND: {
              success: true,
              successType: "成功绑定"
            },
            SUCCESS_JOIN: {
              success: true,
              successType: "成功入会"
            },
            FAIL_NO_ID: {
              success: false
            },
            FAIL_HAS_ID: {
              success: false
            },
            FAIL_NOT_MEMBER: {
              success: false
            },
          };
          const JOIN_VIP_RESULT_MAPPING_TMP = JOIN_VIP_RESULT_MAPPING[key];
          if (JOIN_VIP_RESULT_MAPPING_TMP) {
            const JOIN_VIP_RESULT_MAPPING_FAIL_REASON =
              JOIN_VIP_RESULT_MAPPING_TMP.success ? "" : message;
            RegisterTracker.joinVipResult({
              ...JOIN_VIP_RESULT_MAPPING_TMP,
              failReason: JOIN_VIP_RESULT_MAPPING_FAIL_REASON,
            });
          }
        }
      },
    },
  };
</script>

<style lang="scss">
  @import "./common.scss";

  .message-modal {
    width: 654rpx;
    background: #fff;
    position: relative;

    .top-img {
      display: block;
      width: 654rpx;
	  height: 206rpx;
    }

    .content {
      width: 100%;
      padding-bottom: 96rpx;
    }

    .title {
      text-align: center;
      padding-top: 128rpx;
      font-weight: 500;
      font-family: NotoSansSC-Medium;
      font-size: 36rpx;
			color: #000000;
      line-height: 52rpx;
    }

    .message {
      padding: 20rpx 64rpx 0 64rpx;
      font-size: 28rpx;
      color: #757575;
      font-family:FrankNew-Regular,NotoSansSC-Regular;
      line-height: 48rpx;
      text-align: center;

      &.align-center {
        text-align: center;
        padding-left: 0;
        padding-right: 0;
      }
    }

    .btn-wrap {
      padding-top: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .btn {
        margin-left: 42rpx;

        &:first-child {
          margin-left: 0;
        }
      }

      &.single-btn {
        .btn {
          width: 250rpx;
          height: 74rpx;
        }
      }
    }
		.close{
			position:absolute;
			right: 24rpx;
			top: 24rpx;
			width: 64rpx;
			height: 64rpx;
		}
		.img-icon {
			padding-left: 236.12rpx;
			width: 182rpx;
			height: 57rpx;
		}

    // .close {
    //   margin: 0;
    //   position: absolute;
    //   left: 50%;
    //   bottom: 0;
    //   transform: translate(-50%, 100%);
    //   padding: 24rpx;
    //   font-size: 28rpx;
    //   color: #fff;
    // }
  }
  .big_btn{
    width: 526rpx !important;
  }
</style>
